package com.rui.single;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

//懒汉式单例模式
public class LazyMan {

    private static boolean wurui = false;

    private LazyMan() {
        synchronized (LazyMan.class){
            if(wurui == false){
                wurui = true;
            }
            if(LAZYMAN == null){
                throw new RuntimeException("不要试图使用反射破坏异常");
            }
        }
        System.out.println(Thread.currentThread().getName() + " ok");
    }

    private volatile static LazyMan LAZYMAN;

    public static LazyMan getInstance(){
        if(LAZYMAN == null){
            synchronized (LazyMan.class){
                if(LAZYMAN == null){
                    LAZYMAN = new LazyMan();
                }
            }
        }
        return LAZYMAN;
    }

    //反射
    public static void main(String[] args) throws NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
        LazyMan instance1 = LazyMan.getInstance();
        Constructor<LazyMan> declaredConstructor = LazyMan.class.getDeclaredConstructor(null);

        declaredConstructor.setAccessible(true);
        LazyMan instance2 = declaredConstructor.newInstance();

        System.out.println(instance1);
        System.out.println(instance2);

        System.out.println(instance1 == instance2);
    }
}
